<template>
  <div class="record-manage">
    <!-- 顶部操作区域 -->
    <div class="toolbar">
      <h2 class="section-title">借阅记录</h2>

      <!-- 搜索框和搜索按钮 -->
      <div class="search-bar">
        <input
          v-model="searchKeyword"
          type="text"
          placeholder="请输入图书名或用户名"
          @keyup.enter="handleSearch"
        />
        <button @click="handleSearch" class="blue-btn search-btn">搜索</button>
      </div>
    </div>

    <!-- 表格区域，带滚动容器 -->
    <div class="record-table-wrapper" ref="scrollContainer">
      <table class="record-table">
        <thead>
          <tr>
            <th>借阅人</th>
            <th>图书名</th>
            <th>借出时间</th>
            <th>归还时间</th>
            <th>状态</th>
            <th class="action-column">操作</th>
          </tr>
        </thead>
        <tbody>
          <!-- v-for 渲染分页数据 -->
          <tr v-for="record in records" :key="record.id">
            <td>{{ record.username }}</td>
            <td>{{ record.bookName }}</td>
            <td>{{ formatDate(record.borrowDate) }}</td>
            <td>{{ record.returnDate ? formatDate(record.returnDate) : '未归还' }}</td>
            <td>{{ record.returnDate ? '已归还' : '未归还' }}</td>
            <td class="action-column">
              <div class="action-buttons">
                <button v-if="!record.returnDate" @click="markAsReturned(record)" class="blue-btn">
                  标记归还
                </button>
                <button class="blue-btn disabled-btn" disabled v-else>已归还</button>
              </div>
            </td>
          </tr>
          <tr v-if="records.length === 0 && !isLoading">
            <td colspan="6" style="text-align: center; color: #888">暂无数据</td>
          </tr>
        </tbody>
      </table>

      <!-- 加载中提示 -->
      <div v-if="isLoading" class="loading-indicator">加载中...</div>
      <div v-if="finished && records.length > 0" class="loading-indicator">没有更多数据了</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import axios from 'axios'

interface BorrowRecord {
  id: number
  username: string
  bookName: string
  borrowDate: string
  returnDate: string | null
  status: number // 0: 未归还, 1: 已归还
}

// 响应式变量
const records = ref<BorrowRecord[]>([]) // 借阅记录列表
const total = ref(0) // 总条数（可选）
const page = ref(1) // 当前页码
const pageSize = 20 // 每页20条
const searchKeyword = ref('') // 搜索关键词
const isLoading = ref(false) // 加载状态
const finished = ref(false) // 是否加载完成

// 加载借阅记录，reset = true 表示重新加载（如搜索）
const fetchData = async (reset = false) => {
  if (isLoading.value) return // 防止重复请求

  if (reset) {
    page.value = 1
    records.value = []
    finished.value = false
  }

  isLoading.value = true
  try {
    const res = await axios.get('/api/borrow/search', {
      params: {
        page: page.value,
        pageSize,
        keyword: searchKeyword.value.trim(),
      },
    })

    const data = res.data
    if (data.records && data.records.length > 0) {
      if (reset) {
        records.value = data.records
      } else {
        records.value.push(...data.records)
      }
      total.value = data.total
      page.value++
    } else {
      finished.value = true
    }
  } catch (error) {
    console.error('加载失败:', error)
  } finally {
    isLoading.value = false
  }
}

// 搜索提交
const handleSearch = () => {
  fetchData(true)
}

// 格式化日期
const formatDate = (dateStr: string | null): string => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const y = date.getFullYear()
  const m = String(date.getMonth() + 1).padStart(2, '0')
  const d = String(date.getDate()).padStart(2, '0')
  return `${y}-${m}-${d}`
}

// 标记归还
const markAsReturned = async (record: BorrowRecord) => {
  try {
    const today = new Date().toISOString().split('T')[0]
    const res = await axios.put('/api/borrow/updateStatus', {
      id: record.id,
      returnDate: today,
    })
    if (res.data.success) {
      record.returnDate = today
      record.status = 1
    } else {
      alert('归还失败：' + res.data.message)
    }
  } catch (error) {
    console.error('请求失败：', error)
  }
}

// 监听滚动实现自动加载
const scrollContainer = ref<HTMLElement | null>(null)

const onScroll = () => {
  if (!scrollContainer.value) return
  const el = scrollContainer.value
  const scrollBottom = el.scrollHeight - el.scrollTop - el.clientHeight
  if (scrollBottom < 50 && !isLoading.value && !finished.value) {
    fetchData()
  }
}

onMounted(() => {
  fetchData()
  if (scrollContainer.value) {
    scrollContainer.value.addEventListener('scroll', onScroll)
  }
})

onBeforeUnmount(() => {
  if (scrollContainer.value) {
    scrollContainer.value.removeEventListener('scroll', onScroll)
  }
})
</script>

<style scoped>
.record-manage {
  padding: 0 20px;
}

.toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.section-title {
  font-size: 20px;
  color: #2c3e50;
  border-bottom: 2px solid #3498db;
  padding-bottom: 5px;
}

.search-bar {
  display: flex;
  gap: 8px;
}

.search-bar input {
  padding: 6px 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  min-width: 200px;
}

.blue-btn {
  padding: 6px 12px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  min-width: 80px;
}

.blue-btn:hover {
  background-color: #66b1ff;
}

.record-table-wrapper {
  max-height: 620px;
  overflow-y: auto;
  border: 1px solid #ccc;
  margin-bottom: 20px;
}

.record-table {
  width: 100%;
  border-collapse: collapse;
}

.record-table th,
.record-table td {
  border: 1px solid #ccc;
  padding: 12px;
  text-align: left;
}

.record-table th {
  background-color: #f5f5f5;
}

.action-column {
  width: 140px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.disabled-btn {
  opacity: 0.6;
  cursor: default;
}

.loading-indicator {
  text-align: center;
  color: #888;
  margin: 10px 0;
}

.search-btn {
  user-select: none;
}
</style>
